package com.action.wx.wechat;

import com.action.pc.city.CityAction;
import com.bean.Order_info;
import com.bean.Order_pay;
import com.common.BaseAction;
import com.common.ModelAndJson;
import com.service.order.OrderPayService;
import com.service.order.OrderService;
import com.util.Config;
import com.util.wxpay.RequestHandler;
import com.util.wxpay.Sha1Util;
import com.util.wxpay.TenpayUtil;
import com.util.wxpay.WxUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created by Administrator on 2017/9/15.
 */
@Controller
@RequestMapping("wx/wxpay")
public class WxPayAction extends BaseAction {
    Logger logger = Logger.getLogger(WxPayAction.class);

    @Autowired
    private OrderPayService orderPayService;

    @Autowired
    private OrderService orderService;
    /**
     *
     * @Title: fastPay
     * @Description: 下单页面快速支付 获取微信配置数据
     * @param request
     * @param response
     * @param openId
     * @param orderNo
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/fastPay")
    public String fastPay(HttpServletRequest request, HttpServletResponse response, ModelAndJson modelMap, String openId, String orderNo) throws Exception {

        Order_pay opay = orderPayService.selectByOrderNo(orderNo);
        System.out.println("此时的openId为---------"+openId);
        float money = opay.getPayamount().floatValue()*100;
        System.out.println("money------------------:"+money);
        //金额转化为分为单位
        //订单相关资料
        Order_info orders = orderService.findByOrderNo(orderNo);
        //商户相关资料
        String appid = Config.getString("wx.appid");
        String appsecret =Config.getString("wx.appsecret");
        String partner = Config.getString("wx.partner");;
        String partnerkey =Config.getString("wx.partnerkey");;
        //获取openId后调用统一支付接口https://api.mch.weixin.qq.com/pay/unifiedorder
        String currTime = TenpayUtil.getCurrTime();
        //8位日期
        String strTime = currTime.substring(8, currTime.length());
        //四位随机数
        String strRandom = TenpayUtil.buildRandom(4) + "";
        //10位序列号,可以自行调整。
        String strReq = strTime + strRandom;
        //商户号
        String mch_id = partner;
        //子商户号  非必输
        //String sub_mch_id=partner_child;
        //设备号   非必输
        String device_info="";
        //随机数
        String nonce_str = strReq;
        //商品描述
        //String body = describe;
        //商品描述根据情况修改
        String body = orders.getOrderno();
        //附加数据
        String attach = "";
        //商户订单号
        String out_trade_no = orderNo;
        //int intMoney = (int)money;
        //总金额以分为单位，不带小数点
        int total_fee = (int)money;
        //订单生成的机器 IP
        String spbill_create_ip = request.getRemoteAddr();
        //订 单 生 成 时 间   非必输
//					String time_start ="";
        //订单失效时间      非必输
//					String time_expire = "";
        //商品标记   非必输
//					String goods_tag = "";
        //这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
        //String notify_url =Tools.readTxtFile(WxConst.DOMAIN)+"wx/notify.do";
        String notify_url=Config.getString("wx.notifyurl");
        String trade_type = "JSAPI";
        String openid = openId;
        //非必输
        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("appid", appid);
        packageParams.put("attach", attach);
        packageParams.put("body", body);
        packageParams.put("mch_id", mch_id);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("notify_url", notify_url);
        packageParams.put("openid", openid);
        packageParams.put("out_trade_no", out_trade_no);
        packageParams.put("spbill_create_ip", spbill_create_ip);
        //这里写的金额为1 分到时修改
        packageParams.put("total_fee", "1");
        /*packageParams.put("total_fee", total_fee+"");*/
        packageParams.put("trade_type", trade_type);

        RequestHandler reqHandler = new RequestHandler(request, response);
        reqHandler.init(appid, appsecret, partnerkey);
        String sign = reqHandler.createSign(packageParams);
        logger.info("sign-----------------"+sign);
        String xml="<xml>"+
                "<appid>"+appid+"</appid>"+
                "<attach><![CDATA["+attach+"]]></attach>"+
                "<body><![CDATA["+body+"]]></body>"+
                "<mch_id>"+mch_id+"</mch_id>"+
                "<nonce_str>"+nonce_str+"</nonce_str>"+
                "<notify_url>"+notify_url+"</notify_url>"+
                "<openid>"+openid+"</openid>"+
                "<out_trade_no>"+out_trade_no+"</out_trade_no>"+
                "<sign><![CDATA["+sign+"]]></sign>"+
                "<spbill_create_ip>"+spbill_create_ip+"</spbill_create_ip>"+
                //金额，这里写的1 分到时修改
                "<total_fee>"+1+"</total_fee>"+
                "<trade_type>"+trade_type+"</trade_type>"+
                /*"<total_fee>"+total_fee+"</total_fee>"+*/
                "</xml>";
        System.out.println(xml);
        logger.info("xml------------------:"+xml);
        String allParameters = "";
        try {
            allParameters =  reqHandler.genPackage(packageParams);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String createOrderURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        String prepay_id="";
        try {
            prepay_id = WxUtil.getPayNo(createOrderURL, xml);
            if("".equals(prepay_id)){
                System.out.println("ErrorMsg-----------------:统一支付接口获取预支付订单出错");
                modelMap.setFalse("error","统一支付接口获取预支付订单出错");
                return modelMap.toString();
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        SortedMap<String, String> finalpackage = new TreeMap<String, String>();
        String timestamp = Sha1Util.getTimeStamp();
        String nonceStr2 = nonce_str;
        String prepay_id2 = "prepay_id="+prepay_id;
        String packages = prepay_id2;
        finalpackage.put("appId", appid);
        finalpackage.put("timeStamp", timestamp);
        finalpackage.put("nonceStr", nonceStr2);
        finalpackage.put("package", packages);
        finalpackage.put("signType", "MD5");
        String finalsign = reqHandler.createSign(finalpackage);
        modelMap.put("appId", appid);
        modelMap.put("timeStamp", timestamp);
        modelMap.put("nonceStr", nonceStr2);
        modelMap.put("packages", packages);
        modelMap.put("sign", finalsign);

        return modelMap.toString();
    }

    @ResponseBody
    @RequestMapping(value="/notify")
    public String toNotify(HttpServletRequest request, HttpServletResponse response,ModelAndJson modelMap)throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine())!=null){
            sb.append(line);
        }
        Map map=WxUtil.doXMLParse(sb.toString());
        System.out.println("notifydata:--------------"+map.toString());
        String payResult=(String) map.get("result_code");
        String orderNo=(String) map.get("out_trade_no");
        System.out.println("payResult:--------------"+payResult);
        System.out.println("orderNo:--------------"+orderNo);
        if("SUCCESS".equals(payResult)){
            orderService.callBack(orderNo);
            return "SUCCESS";
        }
        return "FAIL";
    }

    @RequestMapping(value="/result")
    public ModelAndView toResult(ModelAndJson modelMap, String result, String oid, HttpServletRequest request, HttpServletResponse response)throws Exception{
        HashMap<String, Object> paraMap = new HashMap<>();
        Order_info order = orderService.findByOrderNo(oid);
        paraMap.put("ot", order.getOrdertype());
        paraMap.put("oid", oid);
        paraMap.put("order", order);
        paraMap.put("payResult", result);
        if(order.getOrdertype()==1){
            paraMap.put("msg",Config.getString("payresult.msg1"));
            paraMap.put("msg2",Config.getString("payresult.msg2"));
        }
        if(order.getOrdertype()==2){
            paraMap.put("msg",Config.getString("payresult.msg5"));
        }
        if(order.getOrdertype()==4){
            paraMap.put("msg",Config.getString("payresult.msg3"));
            paraMap.put("msg2",Config.getString("payresult.msg4"));
        }

        return new ModelAndView("/wx/order/result", paraMap);
    }

}
